package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate ;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public void set(String key, Object value , Long time , TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    public void setWithLogicalExpire(String key, Object value , Long time , TimeUnit unit){
        RedisData redisData=new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type , Function<ID,R> dbFallback , Long time , TimeUnit unit){
        //1。查询redis
        String key=keyPrefix+id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //是否存在
        if (StrUtil.isNotBlank(json)) {
            //存在
           return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            return null;
        }
        //不存在
        R r=dbFallback.apply(id);
        //是否为空
        if (r == null) {
            this.set(key,"",time,unit);
            return null;
        }
        this.set(key,r,time,unit);
        return r;
    }


}
